import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import dayjs from 'dayjs'
import { saveToStorage, getFromStorage, STORAGE_KEYS } from '../utils/storage'

// 更新存储键名
if (!STORAGE_KEYS.CAMPFIRE_POSTS) {
  STORAGE_KEYS.CAMPFIRE_POSTS = 'time_capsule_campfire_posts'
}

if (!STORAGE_KEYS.CAMPFIRE_REPLIES) {
  STORAGE_KEYS.CAMPFIRE_REPLIES = 'time_capsule_campfire_replies'
}

if (!STORAGE_KEYS.CAMPFIRE_USER_REPUTATION) {
  STORAGE_KEYS.CAMPFIRE_USER_REPUTATION = 'time_capsule_campfire_user_reputation'
}

export const useCampfireStore = defineStore('campfire', () => {
  // 从本地存储加载社区数据
  const savedPosts = getFromStorage(STORAGE_KEYS.CAMPFIRE_POSTS, { posts: [] })
  const savedReplies = getFromStorage(STORAGE_KEYS.CAMPFIRE_REPLIES, { replies: [] })
  const savedUserReputation = getFromStorage(STORAGE_KEYS.CAMPFIRE_USER_REPUTATION, { reputation: 0, badges: [] })
  
  // 存储所有社区帖子
  const posts = ref(savedPosts.posts || [])
  
  // 存储所有回复
  const replies = ref(savedReplies.replies || [])
  
  // 用户声望和徽章
  const userReputation = ref({
    reputation: savedUserReputation.reputation || 0,
    badges: savedUserReputation.badges || []
  })
  
  // 创建新的社区帖子（从思维存档分享）
  function createPost(data) {
    const id = Date.now().toString()
    const newPost = {
      id,
      title: data.title,
      description: data.description,
      tags: data.tags || [],
      archiveId: data.archiveId, // 关联的思维存档ID
      investedTime: data.investedTime || 0, // 已投入时间（分钟）
      blockingPoint: data.blockingPoint || '', // 卡点描述
      createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      status: 'unsolved', // unsolved, solved
      bestAnswerId: null, // 最佳答案ID
      viewCount: 0, // 查看次数
      userId: 'current_user' // 当前用户ID（实际项目中应从用户系统获取）
    }
    
    posts.value.push(newPost)
    return id
  }
  
  // 创建回复
  function createReply(data) {
    const id = Date.now().toString()
    const newReply = {
      id,
      postId: data.postId, // 关联的帖子ID
      content: data.content, // 回复内容
      isExperience: data.isExperience || false, // 是否为经验分享
      createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      likeCount: 0, // 点赞数
      userId: 'current_user' // 当前用户ID（实际项目中应从用户系统获取）
    }
    
    replies.value.push(newReply)
    return id
  }
  
  // 标记最佳答案
  function markBestAnswer(postId, replyId) {
    const post = posts.value.find(p => p.id === postId)
    if (post) {
      post.status = 'solved'
      post.bestAnswerId = replyId
      post.solvedTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
      
      // 增加回答者声望
      const reply = replies.value.find(r => r.id === replyId)
      if (reply && reply.userId === 'current_user') {
        userReputation.value.reputation += 10
        
        // 检查并添加「助人者」徽章
        if (!userReputation.value.badges.includes('helper')) {
          userReputation.value.badges.push('helper')
        }
      }
      
      // 增加提问者声望并添加「破局者」徽章
      if (post.userId === 'current_user') {
        userReputation.value.reputation += 5
        
        if (!userReputation.value.badges.includes('solver')) {
          userReputation.value.badges.push('solver')
        }
      }
    }
  }
  
  // 为回复点赞
  function likeReply(replyId) {
    const reply = replies.value.find(r => r.id === replyId)
    if (reply) {
      reply.likeCount += 1
      
      // 如果是当前用户的回复，增加声望
      if (reply.userId === 'current_user') {
        userReputation.value.reputation += 2
        
        // 检查并添加「经验宝库」徽章（获得超过10个赞）
        const totalLikes = replies.value
          .filter(r => r.userId === 'current_user')
          .reduce((sum, r) => sum + r.likeCount, 0)
          
        if (totalLikes >= 10 && !userReputation.value.badges.includes('experience_treasure')) {
          userReputation.value.badges.push('experience_treasure')
        }
      }
    }
  }
  
  // 从最佳答案创建新容器
  function createContainerFromSolution(postId, containerData) {
    // 此函数将在实现时与containerStore集成
    // 返回创建的容器ID，供后续使用
    return null
  }
  
  // 更新帖子反馈
  function updatePostFeedback(postId, feedback) {
    const post = posts.value.find(p => p.id === postId)
    if (post) {
      post.feedback = feedback
      post.feedbackTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
    }
  }
  
  // 获取所有帖子
  const allPosts = computed(() => posts.value)
  
  // 获取未解决的帖子
  const unsolvedPosts = computed(() => {
    return posts.value.filter(post => post.status === 'unsolved')
  })
  
  // 获取已解决的帖子
  const solvedPosts = computed(() => {
    return posts.value.filter(post => post.status === 'solved')
  })
  
  // 获取帖子的所有回复
  function getPostReplies(postId) {
    return replies.value.filter(reply => reply.postId === postId)
  }
  
  // 按标签搜索帖子
  function searchPostsByTags(tags) {
    if (!tags || tags.length === 0) return posts.value
    
    return posts.value.filter(post => {
      return tags.some(tag => post.tags.includes(tag))
    })
  }
  
  // 按关键词搜索帖子
  function searchPostsByKeyword(keyword) {
    if (!keyword) return posts.value
    
    const lowerKeyword = keyword.toLowerCase()
    return posts.value.filter(post => {
      return (
        post.title.toLowerCase().includes(lowerKeyword) ||
        post.description.toLowerCase().includes(lowerKeyword) ||
        post.blockingPoint.toLowerCase().includes(lowerKeyword)
      )
    })
  }
  
  // 获取热门帖子（按查看次数排序）
  const hotPosts = computed(() => {
    return [...posts.value].sort((a, b) => b.viewCount - a.viewCount)
  })
  
  // 增加帖子查看次数
  function increasePostViewCount(postId) {
    const post = posts.value.find(p => p.id === postId)
    if (post) {
      post.viewCount += 1
    }
  }
  
  // 监听数据变化，保存到本地存储
  watch(
    () => posts.value,
    (newValue) => {
      saveToAPI(STORAGE_KEYS.CAMPFIRE_POSTS, { posts: newValue })
    },
    { deep: true }
  )
  
  watch(
    () => replies.value,
    (newValue) => {
      saveToAPI(STORAGE_KEYS.CAMPFIRE_REPLIES, { replies: newValue })
    },
    { deep: true }
  )
  
  watch(
    () => userReputation.value,
    (newValue) => {
      saveToAPI(STORAGE_KEYS.CAMPFIRE_USER_REPUTATION, newValue)
    },
    { deep: true }
  )
  
  return {
    // 状态
    posts,
    replies,
    userReputation,
    
    // 计算属性
    allPosts,
    unsolvedPosts,
    solvedPosts,
    hotPosts,
    
    // 方法
    createPost,
    createReply,
    markBestAnswer,
    likeReply,
    createContainerFromSolution,
    updatePostFeedback,
    getPostReplies,
    searchPostsByTags,
    searchPostsByKeyword,
    increasePostViewCount
  }
})